package com.jsptpd.smartauth.common.util;

import com.jsptpd.smartauth.modules.business.model.WeChatToken;
import com.jsptpd.smartauth.modules.business.utils.Constants;

import java.io.IOException;
import java.util.Map;

public class WeChatUtil {
    private String WX_URL_SNS_OAUTH2 = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    private String WX_URL_SNS_USERINFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";

    //根据用户授权码code获取token
    public WeChatToken getWxTokenByCode(String code,String appId) throws IOException {
        String errCode="",errMsg="",accessToken="",expireIn="",refreshToken="",scope="",openId="",unionId="";
        //根据appId获取不同的微信id和key
        if(Constants.WX_APP_GROUP.get(appId)==null){
            errCode = Constants.LOGIN_ERRCODE_STATE+"";
            errMsg = Constants.LOGIN_ERRMSG_STATE;
            return new WeChatToken(errCode,errMsg,"","","","","","");
        }
        String wxApp = (String) Constants.WX_APP_GROUP.get(appId);
        String []wxAppId = wxApp.split("\\--");
        //构建微信请求url
        String url = String.format(WX_URL_SNS_OAUTH2, wxAppId[0], wxAppId[1], code);
        //请求access_token
        Map map = HttpUtils.getMap(url);
        if (!map.containsKey("errcode")) { //返回成功
            accessToken = map.get("access_token").toString();
            expireIn = map.get("expires_in").toString();
            refreshToken = map.get("refresh_token").toString();
            scope = map.get("scope").toString();
            openId = map.get("openid").toString();
            unionId = map.get("unionid").toString();

            return new WeChatToken(errCode,errMsg,accessToken,expireIn,refreshToken,scope,openId,unionId);
        } else { //返回失败
            errCode = map.get("errcode").toString();
            errMsg = map.get("errmsg").toString();
            return new WeChatToken(errCode,errMsg,accessToken,expireIn,refreshToken,scope,openId,unionId);
        }
    }

    //根据accessToken获取userInfo
    public Map getUserInfoByToken(String accessToken, String openId) throws IOException {
        String userInfoUrl = String.format(WX_URL_SNS_USERINFO, accessToken, openId);
        return HttpUtils.getMap(userInfoUrl);
    }

    //根据accessToken获取userInfo的nickName
    public String getNickNameByToken(String accessToken, String openId) throws IOException {
        Map userInfoMap = getUserInfoByToken(accessToken,openId);
        return userInfoMap.get("nickname").toString();
    }

}
